# coding=utf-8
from __future__ import print_function, absolute_import

import pandas as pd
from gm.api import *

from tools import dbTool
from tools.selectStockTool import selectStockTool


def testOpenTrendAffectClosePs():
    for code in selectStockTool.getSmallIndexStock():
        testOpenTrendAffectCloseP(code)


def testOpenTrendAffectCloseP(code='SZSE.159531'):
    print("问问")
    """ 低开低走下跌概率:59% """
    history_data = history(symbol='SZSE.159531', frequency='1m', start_time='2024-06-28', end_time='2024-12-24',
                           fields='open, close, low, high, eob', adjust=ADJUST_PREV, df=True)
    openDownCnt = 0
    openDownGo1Cnt = 0
    openDownGo2Cnt = 0
    openDownGo1CloseDownCnt = 0
    openDownGo2CloseDownCnt = 0
    openUpCnt = 0
    openUpGo1Cnt = 0
    openUpGo2Cnt = 0
    openUpGo1CloseUpCnt = 0
    openUpGo2CloseUpCnt = 0
    history_data['date'] = history_data['eob'].dt.date
    history_data['i'] = history_data.index
    groups = history_data.groupby('date')
    count = len(groups)
    for name, group in groups:
        first = group.iloc[0]
        if first['i'] == 0:
            continue
        # 低开
        if first['open'] < history_data.iloc[first['i'] - 1]['close']:  # 开盘价小于前一交易日收盘价
            openDownCnt += 1
            # 低走1分
            if first['open'] > first['close']:  # 当天价格往下走
                openDownGo1Cnt += 1
                # print('低开低走', name)
                if first['open'] > group.iloc[-1]['close']:  # 收盘价低于开盘价, 当日下跌
                    openDownGo1CloseDownCnt += 1
            # 低走2分
            if first['open'] > first['close'] > group.iloc[1]['close']:  # > group.iloc[2]['close']:
                # 监控到32或者33分
                print('低开持续低走', name)
                openDownGo2Cnt += 1
                if first['open'] > group.iloc[-1]['close']:  # 收盘价低于开盘价, 当日下跌
                    openDownGo2CloseDownCnt += 1
                    print('低开持续低走下跌')
        # 高开
        if first['open'] > history_data.iloc[first['i'] - 1]['close']:
            openUpCnt += 1
            # 高走1分
            if first['open'] < first['close']:
                openUpGo1Cnt += 1
                if first['open'] < group.iloc[-1]['close']:  # 收盘价低于开盘价, 当日下跌
                    openUpGo1CloseUpCnt += 1
            # 高走2分
            if first['open'] < first['close'] < group.iloc[1]['close']:
                print('低开持续高走', name)
                openUpGo2Cnt += 1
                if first['open'] < group.iloc[-1]['close']:  # 收盘价低于开盘价, 当日下跌
                    openUpGo2CloseUpCnt += 1

                    # print('低开低走下跌')
    print('低开概率:', openDownCnt / count)
    print('低开低走1分概率:', openDownGo1Cnt / count)
    print('低开低走2分概率:', openDownGo2Cnt / count)
    print('低开低走1分下跌概率:', openDownGo1CloseDownCnt / openDownGo1Cnt)
    print('低开低走2分下跌概率:', openDownGo2CloseDownCnt / openDownGo2Cnt)
    """
    中证2000指数统计: 
    低开低走概率: 0.275
    低开持续低走概率: 0.08
    
    低开低走下跌概率: 0.6
    低开持续低走下跌概率: 0.6
    """
    result = {
        'code': code, 'count': count,
        'openDownRate': round(openDownCnt / count, 2),
        'openUpRate': round(openUpCnt / count, 2),

        'openDownGo1Rate': round(openDownGo1Cnt / count, 2),
        'openDownGo2Rate': round(openDownGo2Cnt / count, 2),
        'openDownGoDown1CloseDownRate': round(openDownGo1CloseDownCnt / openDownGo1Cnt, 2),
        'openDownGoDown2CloseDownCnt': round(openDownGo2CloseDownCnt / openDownGo2Cnt, 2),

        'openUpGoDown1Rate': round(openUpGo1Cnt / count, 2),
        'openUpGoDown2Rate': round(openUpGo2Cnt / count, 2),
        'openUpGoDown1CloseUpRate': round(openUpGo1CloseUpCnt / openUpGo1Cnt, 2),
        'openUpGoDown2CloseUpCnt': round(openUpGo2CloseUpCnt / openUpGo2Cnt, 2),
    }
    result = pd.DataFrame([result])
    # 保存到数据库
    dbTool.saveAll('rs_first_price', result, '评估初始行情对整日行情的影响')


# 策略中必须有init方法
def init(context):
    testOpenTrendAffectCloseP()
    # testOpenDownGoDayDownPs()
    pass


if __name__ == '__main__':
    '''
        strategy_id策略ID, 由系统生成
        filename文件名, 请与本文件名保持一致
        mode运行模式, 实时模式:MODE_LIVE回测模式:MODE_BACKTEST
        token绑定计算机的ID, 可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
        backtest_match_mode市价撮合模式，以下一tick/bar开盘价撮合:0，以当前tick/bar收盘价撮合：1
        '''
    print("问问")
    run(strategy_id='b40aa9ba-c11d-11ef-8a13-e8c829bed8c8',
        filename='small_index_gm.py',
        mode=MODE_BACKTEST,
        token='fd322a3568282f2404e1602e95a8861fe5e36b00',
        backtest_start_time='2020-11-01 08:00:00',
        backtest_end_time='2020-11-10 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001,
        backtest_match_mode=1)
